from PyQt5.QtWidgets import QTableWidget,QTableWidgetItem,QCheckBox,QWidget,QHBoxLayout,QMenu,QAction,QApplication
from PyQt5.QtGui import QPixmap,QPen,QBrush,QColor
from PyQt5.QtCore import Qt,QRectF,QPointF,pyqtSignal
import resources
class CheckBoxItem(QCheckBox):
    def __init__(self, select=True,color='#000000'):
        super().__init__()
        self.setChecked(select)
        style = f"""
            QCheckBox {{
                border: 1px solid #0000001f;
                width: 18px;
                height: 18px;
            }}
            QCheckBox::indicator:checked {{
                background-color: {color};
                border-radius: 3px;
                border: 1px solid #999999;
            }}
        """
        self.setStyleSheet(style)


class ColorTable(QTableWidget):
    rect_selected = pyqtSignal(dict)  # 添加信号用于发送矩形参数
    
    def __init__(self):
        super().__init__()
        self.setColumnCount(3)
         # 设置表头
        headers = ["状态", "颜色", "坐标"]
        self.setHorizontalHeaderLabels(headers)
        # 设置第1列宽度为150像素
        self.setColumnWidth(0, 50)
        # 设置第2列宽度为100像素
        self.setColumnWidth(1, 80)
        # 设置第3列宽度为200像素
        self.setColumnWidth(2, 80)
        #数据格式：[[1,TRUE,'#000000',(0,0)]]
        self.data = []
        self.num = 1
        self.setEditTriggers(QTableWidget.NoEditTriggers)

         # 启用右键菜单
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.showContextMenu)

    def addRow(self,color,pos):
        self.data.append([self.num,True,color,pos])
        self.num += 1
        self.renderTable()

    def renderTable(self):
        self.setRowCount(len(self.data))
        for i, item in enumerate(self.data):
            # # 第0列：勾选框单元格
            # check_item = CheckBoxItem(item[1],item[2])
            # # 创建容器widget和布局
            # container = QWidget()
            # layout = QHBoxLayout(container)
            # layout.addWidget(check_item)
            # # 设置布局对齐方式为居中
            # layout.setAlignment(Qt.AlignCenter)
            # # 移除布局周围的边距
            # layout.setContentsMargins(0, 0, 0, 0)

            # self.setCellWidget(i, 0, container)

             # 第0列：勾选框单元格
            check_item = QTableWidgetItem("")
            # 设置为可勾选状态
            check_item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
            # 默认未勾选（可选：设置为默认勾选 Qt.Checked）
            check_item.setCheckState(Qt.Checked if item[0] else Qt.Unchecked)
           
            color = QColor(item[2])
            check_item.setBackground(QBrush(color))

            self.setItem(i, 0, check_item)

            self.setItem(i, 1, QTableWidgetItem(item[2].upper()))
            self.setItem(i, 2, QTableWidgetItem("{},{}".format(*item[3])))

    def showContextMenu(self, position):
        try:
            # 创建右键菜单
            menu = QMenu()
            
            # 添加菜单项
            copy_color = QAction("复制颜色", self)
            copy_pos = QAction("复制坐标", self)
            del_row = QAction("删除数据", self)
            clear_row = QAction("清空数据", self)
            
            # 绑定菜单项的触发事件
            copy_color.triggered.connect(self.copyColor)
            copy_pos.triggered.connect(self.copyPos)
            del_row.triggered.connect(self.deleteCell)
            clear_row.triggered.connect(self.clearCell)
           
            # 将菜单项添加到菜单
            menu.addAction(copy_color)
            menu.addAction(copy_pos)
            menu.addSeparator()  # 添加分隔线
            menu.addAction(del_row)
            menu.addAction(clear_row)
            # 在鼠标位置显示菜单
            menu.exec_(self.mapToGlobal(position))
        except KeyboardInterrupt:
            # 捕获键盘中断异常，确保应用程序不会崩溃
            pass
        except Exception as e:
            # 捕获其他可能的异常
            print(f"右键菜单错误: {str(e)}")
            pass

    def copyColor(self):
        # 获取选中的单元格
        selected_items = self.selectedItems()
        if selected_items:
            clipboard = QApplication.clipboard()
            clipboard.setText(self.data[selected_items[0].row()][2])
          

    def copyPos(self):
        # 获取选中的单元格
        selected_items = self.selectedItems()
        if selected_items:
           clipboard = QApplication.clipboard()
           clipboard.setText("{},{}".format(*self.data[selected_items[0].row()][3]))

    def deleteCell(self):
        # 获取选中的单元格
        selected_items = self.selectedItems()
        if selected_items:
            # 获取选中的行索引（使用集合确保只处理唯一的行）
            rows_to_delete = set()
            for item in selected_items:
                rows_to_delete.add(item.row())
            
            # 转换为列表并按降序排序，这样删除时不会影响后续索引
            sorted_rows = sorted(rows_to_delete, reverse=True)
            
            # 从数据列表中删除对应的行
            for row in sorted_rows:
                if 0 <= row < len(self.data):
                    del self.data[row]
            
            # 重新渲染表格
            self.renderTable()
            
            # 清空选择
            self.clearSelection()

    def clearCell(self):
        # 清空数据列表
        self.data = []
        # 重置序号
        self.num = 1
        # 重新渲染表格
        self.renderTable()
        # 清空选择
        self.clearSelection()

        
   

   